import React from 'react'
export default class App2 extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            comments: [
                { id: 1, name: '黄健翔', content: '葡萄牙第一' },
                { id: 2, name: '董路', content: '波兰第一' },
                { id: 3, name: '段暄', content: '法国第一' },

            ],
            userContent: '',
            userName: '',
        }
    }

    //react中多表单公用改变数据的方法
    handleForm = (e) => {
        this.setState({
            // userName
            // userContent
            [e.target.name]: e.target.value,
        }, () => {
            console.log('userContent', this.state.userContent);
            console.log('userName', this.state.userName);
        })
    }
    // 点击发表评论的方法
    addComment = () => {
        const { comments, userContent, userName } = this.state
        const newComments = [{
            id: Math.random(),
            name: userName,
            content: userContent
        },
        ...comments]
        this.setState({
            comments: newComments,
            userContent: '',
            userName: ''
        })
    }

    render() {
        return (
            <div>
                <div>
                    <input name='userName'
                        onChange={this.handleForm}
                        type='text'
                        value={this.state.userName}
                        placeholder='请输入评论人' /><br />
                    <textarea name='userContent' cols='50'
                        rows='10'
                        onChange={this.handleForm}
                        value={this.state.userContent}></textarea>

                </div>
                <button onClick={this.addComment}>点击提交</button>
                <div>
                    <ul>
                        {this.state.comments.length == 0 ? (<div>暂无评论，快去评论吧</div>) : (this.state.comments.map(item => (<li key={item.id}><h2>评论人：{item.name}</h2><p>评论内容：{item.content}</p></li>)))}
                    </ul>
                </div>
            </div>
        )
    }
}
